﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using deezer.sdk.windowsphone.Helpers;

namespace deezer.sdk.windowsphone
{
    public delegate void SearchResponseEventHandler(object sender, EventArgsSearch e);

    public class Search
    {
        HttpWebRequest request;

        public event SearchResponseEventHandler SearchResponse;

        protected virtual void SearchResponseCheck(EventArgsSearch e)
        {
            if (SearchResponse != null)
                SearchResponse(this, e);
        }

        public void SearchAsync(String q)
        {
            Uri uriId = new Uri(String.Format(@"http://api.deezer.com/2.0/search?q={0}&output=xml", q));
            request = HttpWebRequest.CreateHttp(uriId);
            request.Method = "GET";
            request.BeginGetResponse(new AsyncCallback(SearchResponseIntern), null);
        }

        private void SearchResponseIntern(IAsyncResult result)
        {
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
                    {
                        EventArgsSearch e = new EventArgsSearch(Converter.ConvertJsonToTypeResultSearch(responseStream.ReadToEnd()));
                        SearchResponseCheck(e);
                    }
                }
            }
        }

        
    }
}
